package com.hanxiaozhang.threadbase1ndedition.no1synchronizedkeyword;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈锁异常自动释放〉
 *
 * @author hanxinghua
 * @create 2021/11/9
 * @since 1.0.0
 */
public class No6SynchExceptionRelease {

    private int count = 0;

    public synchronized void method() {
        System.out.println(Thread.currentThread().getName() + " start!");
        while (true) {
            count++;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 5) {
                // 此处抛出异常，锁将被释放
                int i = 1 / 0;
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        No6SynchExceptionRelease example = new No6SynchExceptionRelease();
        new Thread(example::method, "THREAD-1").start();
        TimeUnit.SECONDS.sleep(3);
        new Thread(example::method, "THREAD-2").start();


    }


}
